/**
 *
 */
package com.storm.lib.generator;

//import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;


import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;

import com.storm.lib.base.BaseDAO;
import com.storm.lib.base.BaseJavaExecuter;
import com.storm.lib.bean.SheetBean;
import com.storm.lib.type.SystemType;
import com.storm.lib.util.BeanUtil;
import com.storm.lib.util.DBUtil;
import com.storm.lib.util.ExcelUtil;
import com.storm.lib.util.FileUtil;




/**
 * 类功能: 用来创建数据库表
 * @author johnny
 * @version 2010-10-27
 */
@Controller
public class DbBuilder extends BaseJavaExecuter{
	protected final Logger logger = Logger.getLogger(getClass());
	private static DbBuilder dBBuilder;

	public static DbBuilder getInstance(){
		if(dBBuilder==null){
			dBBuilder = new DbBuilder();
		}
		return dBBuilder;
	}
	
	
	/**
	 * 
	 * 方法功能:执行
	 * 更新时间:2011-8-26, 作者:johnny
	 * @param reCreateTable
	 * @param sheetName
	 * @param file
	 * @param language
	 */
	public void execute(boolean reCreateTable,String sheetName,String language) {
		BaseDAO baseDAO = (BaseDAO) BeanUtil.getBean("baseDAO");
		FileInputStream in=null;
		HSSFWorkbook workBook = FileUtil.getGameExcelData();
		for (int i = 0; i < workBook.getNumberOfSheets(); i++) {
			HSSFSheet sheet = workBook.getSheetAt(i);
			if(sheet.getSheetName().contains("Tag-structure-")==false){
				continue;
			}
			logger.debug(sheet.getSheetName());
			if(sheet.getSheetName().equals(sheetName)==false){
				continue;
			}
			SheetBean sheetBean = ExcelUtil.getSheetBeanBySheet(sheet,language);
			String dbName = (String)sheetBean.getParameters().get(0);
			String tableName = (String)sheetBean.getParameters().get(1);
			String createDBStatament = DBUtil.getCreateDatabaseIfExists(dbName);
			baseDAO.executeSql(createDBStatament);
			String dropTableStatament = DBUtil.getDropTableIfExists(dbName,tableName);
			String createTableStatament = DBUtil.getCreateTableStrByTagStructure(dbName, sheetBean);
			List<String> insertSampleStatament = DBUtil.getInsertSampleStrByTagStructure(dbName, sheetBean);

			if(reCreateTable==true){
				baseDAO.executeSql(dropTableStatament);
				baseDAO.executeSql(createTableStatament);
			}
			if(insertSampleStatament==null || insertSampleStatament.size()==0){
				return;
			}			
			if(insertSampleStatament!=null){
				baseDAO.batchUpdate(insertSampleStatament.toArray(new String[insertSampleStatament.size()]));
			}
			logger.debug("完成插入操作");
		}
	}


}
